package com.retail.lottery.colalottery.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.retail.lottery.colalottery.entity.OrderCallback;
import com.retail.lottery.colalottery.entity.OrderDetail;
import com.retail.lottery.colalottery.entity.WechatCustomer;
import com.retail.lottery.colalottery.enums.DeleteStatusEnum;
import com.retail.lottery.colalottery.enums.OrderCallbackStatusEnum;
import com.retail.lottery.colalottery.enums.OrderCallbackSyncStatusEnum;
import com.retail.lottery.colalottery.mapper.WechatCustomerMapper;
import com.retail.lottery.colalottery.service.OrderCallbackService;
import com.retail.lottery.colalottery.service.OrderDetailService;
import com.retail.lottery.colalottery.mapper.OrderDetailMapper;
import com.retail.lottery.colalottery.vo.ResultVO;
import com.retail.lottery.colalottery.vo.request.OrderDetailRequestVo;
import com.retail.lottery.colalottery.vo.response.OrderDetailResponseVo;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
* @author jarvis.zhang
* @description 针对表【order_detail(订单明细表)】的数据库操作Service实现
* @createDate 2025-06-06 15:52:30
*/
@Service
public class OrderDetailServiceImpl extends ServiceImpl<OrderDetailMapper, OrderDetail>
    implements OrderDetailService{

    @Resource
    private WechatCustomerMapper wechatCustomerMapper;
    @Resource
    private OrderCallbackService orderCallbackService;

    @Override
    public ResultVO<?> orderList(OrderDetailRequestVo orderDetailVo) {
        WechatCustomer wechatCustomer = wechatCustomerMapper.selectOne(new LambdaQueryWrapper<WechatCustomer>()
                .eq(WechatCustomer::getOpenId, orderDetailVo.getOpenId())
                .eq(WechatCustomer::getIsDel, DeleteStatusEnum.no_del.getCode())
                .last("limit 1"));
        List<OrderDetailResponseVo> orderDetailResponseVos = Lists.newArrayList();
        if (Objects.isNull(wechatCustomer)) {
            return ResultVO.succ(orderDetailResponseVos);
        }
        Set<Integer> callbackIds = orderCallbackService.getBaseMapper().selectList(new LambdaQueryWrapper<OrderCallback>()
                        .eq(OrderCallback::getWechatCustomerId, wechatCustomer.getId())
                        .eq(OrderCallback::getSyncStatus, OrderCallbackSyncStatusEnum.SYNC_SUCCESS.getStatus())
                        .eq(OrderCallback::getIsDel, DeleteStatusEnum.no_del.getCode()))
                .stream().map(OrderCallback::getId).collect(Collectors.toSet());
        if(callbackIds.size() == 0){
            return ResultVO.succ(orderDetailResponseVos);
        }
        Map<Date, List<OrderDetail>> orderGroupByMap = baseMapper.selectList(new LambdaQueryWrapper<OrderDetail>()
                        .eq(OrderDetail::getCallbackId, callbackIds)
                //TODO.eq(OrderDetail::getSetupId, orderDetailVo.getSetupId()
        ).stream().collect(Collectors.groupingBy(OrderDetail::getOrderFinishTime));
        if(CollectionUtils.isEmpty(orderGroupByMap)){
            return ResultVO.succ(orderDetailResponseVos);
        }
        orderGroupByMap.keySet().stream().sorted(Comparator.reverseOrder()).forEach(date -> {
            List<OrderDetail> orderDetails = orderGroupByMap.get(date);
            OrderDetailResponseVo responseVo = new OrderDetailResponseVo();
            responseVo.setOrderTime(date);
            responseVo.setStatus(orderDetails.get(0).getOrderStatus());
            responseVo.setTotalActualPrice(String.valueOf(orderDetails.stream()
                    .mapToLong(order -> {
                        try {
                            return Long.valueOf(order.getActualPrice());
                        } catch (NumberFormatException e) {
                            return 0L; // 非法数据按 0 处理
                        }
                    })
                    .sum()));
            responseVo.setEffectiveAmount(String.valueOf(orderDetails.stream()
                    .filter(order -> order.getIsEffective() == 1)
                    .mapToLong(order -> {
                        try {
                            return Long.valueOf(order.getActualPrice());
                        } catch (NumberFormatException e) {
                            return 0L; // 非法数据按 0 处理
                        }
                    })
                    .sum()));
            responseVo.setOrderList(orderDetails.stream().map(order -> {
                OrderDetailResponseVo.OrderDetailVo vo = new OrderDetailResponseVo.OrderDetailVo();
                vo.setSkuName(order.getSkuName());
                vo.setSkuSpec(order.getSkuSpec());
                vo.setActualPrice(String.valueOf(order.getActualPrice()));
                return vo;
            }).collect(Collectors.toList()));
            orderDetailResponseVos.add(responseVo);
        });
        return ResultVO.succ(orderDetailResponseVos);
    }
}




